package com.gkd.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gkd.constant.MessageConstant;
import com.gkd.constant.RoleConstant;
import com.gkd.constant.StatusContant;
import com.gkd.exception.AccountNotFoundException;
import com.gkd.pojo.dto.*;
import com.gkd.pojo.entity.User;
import com.gkd.pojo.vo.UserLoginVO;
import com.gkd.pojo.vo.UserVO;
import com.gkd.properties.JwtProperties;
import com.gkd.result.PageResult;
import com.gkd.result.Result;
import com.gkd.service.UserService;
import com.gkd.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 管理员相关接口
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 创建新用户
     * @param userDTO
     * @return
     */
    @PostMapping
    public Result add(@RequestBody UserDTO userDTO){
        log.info("用户添加:{}",userDTO);
        userService.add(userDTO);
        return Result.success();
    }

    /**
     * 用户分页查询
     * @param userPageQueryDTO
     * @return
     */
    @GetMapping
    public Result<PageResult> page(UserPageQueryDTO userPageQueryDTO){
        log.info("用户分页查询,参数为：{}",userPageQueryDTO);
        PageResult pageResult=userService.pageQuery(userPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录：{}",userLoginDTO);
        User user =userService.login(userLoginDTO);
        if(user.getRole().equals(RoleConstant.ADMIN)){
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId",user.getUserId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);

            UserLoginVO userLoginVO = UserLoginVO.builder()
                    .userId(user.getUserId())
                    .username(user.getUsername())
                    .name(user.getName())
                    .role(user.getRole())
                    .token(token)
                    .build();

            return Result.success(userLoginVO);
        }else {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

    }

    /**
     * 根据id获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public Result<UserVO> getById(@PathVariable Integer userId){
        log.info("根据id获取用户信息:{}",userId);

        UserVO userVO = new UserVO();
        User user = userService.getById(userId);
        BeanUtils.copyProperties(user,userVO);

        return Result.success(userVO);
    }

    /**
     * 更新用户信息
     * @param userDTO
     * @return
     */
    @PutMapping
    public Result updateById(@RequestBody UserDTO userDTO){
        log.info("更新用户信息:{}",userDTO);

        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        if (StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        userService.updateById(user);

        return Result.success();
    }

    /**
     * 批量删除用户
     * @param userIds
     * @return
     */
    @DeleteMapping
    public Result deleteByIds(@RequestBody List<Integer> userIds){
        log.info("批量删除用户:{}",userIds);
        //userService.removeByIds(userIds);

        List<User> userList = new ArrayList<>();
        userIds.forEach(userId->{
            User user = User.builder()
                    .userId(userId)
                    .status(StatusContant.USER_FALSE)
                    .build();
            userList.add(user);
        });
        //修改用户状态
        userService.updateBatchById(userList);
        return Result.success();
    }

    /**
     * 更改管理员状态
     * @param status
     * @param userId
     * @return
     */
    @PutMapping("/status/{status}")
    public Result status(@PathVariable Integer status,Integer userId){
        log.info("启用或禁用管理员:adminId={},status={}",userId,status==0?"禁用":"启用");

        User user = User.builder()
                .userId(userId)
                .status(status)
                .build();

        userService.updateById(user);

        return Result.success();
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @PutMapping("/pwd")
    public Result updatePassword(@RequestBody PasswordDTO passwordDTO) {
        // 日志记录用户ID和操作，而非密码
        log.info("用户ID:{}尝试更新密码", passwordDTO.getUserId());
        
        // 查找用户
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_id", passwordDTO.getUserId());
        User user = userService.getOne(qw);

        if (user != null) {
            // 使用MD5比较密码
            String inputPasswordMd5 = DigestUtils.md5DigestAsHex(passwordDTO.getPassword().getBytes());
            if (user.getPassword().equals(inputPasswordMd5)) {
                // 更新密码
                String newMd5Password = DigestUtils.md5DigestAsHex(passwordDTO.getNewPassword().getBytes());
                user.setPassword(newMd5Password);
                userService.updateById(user);
                return Result.success("密码更新成功");
            } else {
                return Result.error("当前密码错误");
            }
        } else {
            return Result.error("用户不存在或密码错误");
        }
    }

    /**
     * 验证token
     */
    @GetMapping("/verifyToken")
    public Result verifyToken(){
        return Result.success();
    }
}
